package com.qianfeng.android.baoman.fragment;


import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.qianfeng.android.baoman.Constants;
import com.qianfeng.android.baoman.LoginActivity;
import com.qianfeng.android.baoman.MainActivity;
import com.qianfeng.android.baoman.R;
import com.qianfeng.android.baoman.adapter.TopicArticleAdapter;
import com.qianfeng.android.baoman.model.Article;
import com.qianfeng.android.baoman.model.Cinema;
import com.qianfeng.android.baoman.model.LoginUser;
import com.qianfeng.android.baoman.model.Other;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class UserFragment extends Fragment implements View.OnClickListener, PullToRefreshBase.OnRefreshListener2<ListView> {

    private MainActivity context;
    private int pageCount;
    private LinearLayout load_layout;
    private ImageView defaultImage;

    private PullToRefreshListView refreshListView;
    private ListView listView;
    //设置加载延迟时间
    private Handler handler = new Handler();
    private List<Article> articleList;
    private TopicArticleAdapter adapter;
    private ImageView userPhoto;
    private TextView userName;
    private ImageView coins;
    private TextView textCoins;
    private ImageButton loginBtn;
    private RadioButton rbEnjoy;
    private RadioButton rbFocus;
    private RadioButton rbFuns;
    private RadioButton rbDetail;

    public UserFragment() {
        // Required empty public constructor
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity != null) {
            context = (MainActivity) activity;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View ret = inflater.inflate(R.layout.activity_user_detail, container, false);
        pageCount = 1;
        context.setActionBarTitle("我的暴走");
        context.setFunctionVisible(true);
        ImageButton fun = (ImageButton) context.findViewById(R.id.action_function);
        fun.setImageResource(R.drawable.my_center_setting_btn);
        //加载数据时显示
        load_layout = (LinearLayout) ret.findViewById(R.id.load_layout);
        defaultImage = (ImageView) ret.findViewById(R.id.activity_user_detail_default);

        View view = ret.findViewById(R.id.top);
        view.setVisibility(View.GONE);


        refreshListView =
                (PullToRefreshListView) ret.findViewById(R.id.activity_see_other_pullRoRefreshList);
        listView = refreshListView.getRefreshableView();
        refreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        Drawable drawable = getResources().getDrawable(R.drawable.arrow_down);
        refreshListView.setLoadingDrawable(drawable);
        // 设置加载中的标题
        refreshListView.setRefreshingLabel("加载...");
        // 设置“松开”提醒
        refreshListView.setReleaseLabel("松开可以刷新");
        refreshListView.setOnRefreshListener(this);
        view = LayoutInflater.from(context).inflate(R.layout.item_user_detail_header, null, false);
        listView.addHeaderView(view);
        setViewHeader(view);
        articleList = new ArrayList<>();
        adapter = new TopicArticleAdapter(context, articleList);

        listView.setAdapter(adapter);
        listView.setAdapter(adapter);
        listView = refreshListView.getRefreshableView();

        return ret;
    }

    private void setViewHeader(View view) {
        final View view1 = view.findViewById(R.id.item_user_detail_view1);
        final View view2 = view.findViewById(R.id.item_user_detail_view2);
        userPhoto = (ImageView) view.findViewById(R.id.item_user_detail_header);
        userPhoto.setImageResource(R.drawable.people_center_not_login_left);
        userName = (TextView) view.findViewById(R.id.item_user_detail_userName);
        userName.setVisibility(View.GONE);
        coins = (ImageView) view.findViewById(R.id.item_user_detail_coins);
        coins.setVisibility(View.GONE);
        textCoins = (TextView) view.findViewById(R.id.item_user_detail_coins_count);
        textCoins.setVisibility(View.GONE);

        ImageButton pager = (ImageButton) view.findViewById(R.id.item_user_detail_pager);
        pager.setVisibility(View.GONE);
        ImageButton focus = (ImageButton) view.findViewById(R.id.item_user_detail_focus);
        focus.setVisibility(View.GONE);

        loginBtn = (ImageButton) view.findViewById(R.id.item_user_detail_login);
        loginBtn.setVisibility(View.VISIBLE);
        loginBtn.setOnClickListener(this);

        rbEnjoy = (RadioButton) view.findViewById(R.id.item_user_detail_enjoy);
        rbEnjoy.setVisibility(View.VISIBLE);

        rbFocus = (RadioButton) view.findViewById(R.id.item_user_detail_radio_focus);
        rbFuns = (RadioButton) view.findViewById(R.id.item_user_detail_radio_funs);
        rbDetail = (RadioButton) view.findViewById(R.id.item_user_detail_radio_moreDetail);


        RadioGroup rg = (RadioGroup) view.findViewById(R.id.item_user_detail_shenzuo);


        if (rg != null) {
            rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    int count = group.getChildCount();
                    int position = -1;
                    for (int i = 0; i < count; i++) {
                        View view = group.getChildAt(i);
                        if (view instanceof RadioButton) {
                            RadioButton rb = (RadioButton) view;
                            if (rb.isChecked()) {
                                position = i;
                                break;
                            }
                        }
                    }
                    if (position != -1) {
                        switch (position) {
                            case 0:
                                view1.setVisibility(View.VISIBLE);
                                view2.setVisibility(View.INVISIBLE);
                                defaultImage.setImageResource(R.drawable.no_article_img);
                                break;
                            case 1:
                                view1.setVisibility(View.INVISIBLE);
                                view2.setVisibility(View.VISIBLE);
                                defaultImage.setImageResource(R.drawable.no_pubarticle_img);
                                break;
                        }
                    }
                }
            });
            View rgChildAt = rg.getChildAt(0);
            if (rgChildAt instanceof RadioButton) {
                RadioButton rb = (RadioButton) rgChildAt;
                rb.setChecked(true);
            }
        }
    }


    @Override
    public void onClick(View v) {
        context.onClick(v);
        int id = v.getId();
        switch (id) {
            case R.id.item_user_detail_login:
                Intent intent = new Intent(context, LoginActivity.class);
                startActivityForResult(intent, 23);
                break;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Toast.makeText(context, "登陆成功！", Toast.LENGTH_SHORT);
        Constants instance = Constants.getInstance();
        LoginUser user = instance.getUser();
        if (user != null) {
            String token = user.getAccess_token();
            int user_id = user.getUser_id();
            String client_id = user.getClient_id();
            String url = Constants.getLoginUserDetail(client_id, token, user_id);
            getUserDetail(url);
        }
    }

    private void getUserDetail(String url) {
        load_layout.setVisibility(View.VISIBLE);
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET,
                url,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> objectResponseInfo) {
                        String result = objectResponseInfo.result;
                        try {
                            //结束刷新
                            refreshListView.onRefreshComplete();
                            JSONObject object = new JSONObject(result);
                            Other other = new Other();
                            other.parseJSON(object);
                            setView(other);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        load_layout.setVisibility(View.GONE);
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        Toast.makeText(context, "加载失败，网络问题", Toast.LENGTH_SHORT).show();
                        load_layout.setVisibility(View.GONE);
                        refreshListView.setMode(PullToRefreshBase.Mode.DISABLED);
                    }
                });
    }

    private void setView(Other other) {
        userName.setText(other.getLogin());
        userName.setVisibility(View.VISIBLE);
        coins.setVisibility(View.VISIBLE);
        textCoins.setText(Integer.toString(other.getSalary()));
        textCoins.setVisibility(View.VISIBLE);
        loginBtn.setVisibility(View.GONE);
        userPhoto.setImageResource(R.drawable.people_center_img_bg);
        rbFocus.setText(Integer.toString(other.getFavorites_count()));
        rbFuns.setText(Integer.toString(other.getFriends_count()));

    }
}
